import { defineStore } from 'pinia'
import { ref } from 'vue'
import { login, getInfo } from '@/api/login'
 

// 用户
const useUserStore = defineStore('user', () => {
    const token = ref<string>('') // token
    const userInfo = ref<IUserInfo>() // 用户信息
    const role = ref<IRole>() // 角色信息
    // 用户登录方法 
    const loginAction = async (arg: ILoginAccount) => {
        const { status, message, token: responseToken} = await login(arg)
        // 登录成功
        if(status === 200){
            token.value = responseToken as string
            return {
                success: true
            }
        }
        // 登录失败
        token.value = ''
        return {
            success: false,
            message
        }
    }

    // 用户登录信息
    const getUserInfoAction = async () => {
        const result = await getInfo()
        // console.log(result)
        if(result.status === 200){
            userInfo.value = result.userInfo
            role.value = result.roles[0]
        }else {
            userInfo.value = undefined,
            role.value = undefined
        }
    }
    // 
    return {
        token,
        userInfo,
        role,
        loginAction,
        getUserInfoAction
    }
}, {
    persist: {
        storage: sessionStorage,
        pick: ['token']
    }
})

export default useUserStore